<template>
  <div>
    <dd-table :column-labels="columnLabels" :api-name="apiName" :model="model">
      <template #dialogForm>
        <el-button type="primary" icon="Plus" @click="dialogVisible = true">
          添加
        </el-button>
        <el-dialog
          v-model="dialogVisible"
          title="添加"
          :close-on-click-modal="false"
        >
          <el-form
            ref="pesticideRef"
            :rules="rules"
            :model="model"
            label-width="4em"
          >
            <el-form-item prop="pesticideId" :label="$t('pesticideId')">
              <div class="row jcfe w100">
                <el-select
                  v-model="model.pesticideId"
                  filterable
                  clearable
                  @scroll="loadMore"
                  v-loadmore="loadMore"
                  :teleported="false"
                  class="pr-1"
                >
                  <el-option
                    v-for="item in pesticides"
                    :key="item.id"
                    :label="`${item.name}-${item.netContent}`"
                    :value="item.id"
                  />
                  <!-- 虚拟滚动区域，用于触发加载更多 -->
                  <div
                    class="virtual-dropdown"
                    v-if="hasMore"
                    @scroll="handleScroll"
                    ref="virtualDropdown"
                  >
                    <!-- 加载更多提示（可选） -->
                    <div v-if="isLoading" class="loading-more">加载中...</div>
                  </div>
                </el-select>
                <el-button
                  icon="Plus"
                  @click="$router.push('product')"
                  :type="pesticides.length ? '' : 'primary'"
                  >添加产品</el-button
                >
              </div>
            </el-form-item>

            <el-form-item
              prop="productSpecificationCode"
              :label="$t('productSpecificationCode')"
            >
              <el-input-number
                v-model="model.productSpecificationCode"
                :min="1"
                :max="999"
              />
            </el-form-item>

            <el-form-item prop="count" :label="$t('count')">
              <el-input-number :min="1" :max="3000000" v-model="model.count" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">
                {{ $t('Cancel') }}</el-button
              >
              <el-button type="primary" @click="onSubmit">{{
                $t('Confirm')
              }}</el-button>
            </span>
          </template>
        </el-dialog>
      </template>
      <template #operate="{ row }">
        <el-button icon="View" @click="preview(row)" v-debounced
          >预览</el-button
        >
        <el-button icon="Download" @click="getFileURL(row)" v-debounced
          >下载</el-button
        >
        <el-button
          icon="Delete"
          type="danger"
          @click="onDelete(row)"
          v-debounced
          >删除</el-button
        >
      </template>
    </dd-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject } from 'vue';
import { rules } from '@/libs/Rules';
import { ElLoading, FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { shios } from '@/api/Shios';
const reload = inject<Function>('reload');
const dialogVisible = ref(false);
const isLoading = ref(false);
const hasMore = ref(false);
const pesticideRef = ref<FormInstance>();
const apiName = ref('BatchQRCode');
const columnLabels = ['fileName', 'createTime'];
const router = useRouter();

const model = ref({
  productSpecificationCode: 0,
  count: 0,
  pesticideId: undefined,
  host:
    window.location.origin +
    router.options.history.base +
    '/pesicideinfo/details/',
});

type Pesticide = {
  id: number;
  name: string;
  netContent: string;
};
const vLoadmore = {
  mounted: (el: HTMLElement, binding: any) => {
    console.log(123);

    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown__wrap');

    if (SELECTWRAP_DOM) {
      SELECTWRAP_DOM.addEventListener('scroll', function () {
        const condition =
          SELECTWRAP_DOM.scrollHeight - SELECTWRAP_DOM.scrollTop <=
          SELECTWRAP_DOM.clientHeight;

        if (condition) {
          binding.value();
        }
      });
    }
  },
};
async function loadMore() {
  console.log('滚动到底部了2');
  let lastId = pesticides.value[pesticides.value.length - 1]?.id;
  const res = await shios.get<Array<Pesticide>>('pesticides', {
    query: { lastId },
  });
  console.log(res);

  if (res.data) {
    pesticides.value = [...pesticides.value, ...res.data];
    hasMore.value = true;
  }
}
const pesticides = ref<Pesticide[]>([]);
const res = await shios.get<Array<Pesticide>>('pesticides');
if (res.data) {
  pesticides.value = res.data;
  hasMore.value = true;
}

function handleScroll() {
  console.log(123);
}
/**
 * 提交
 */
async function onSubmit() {
  await pesticideRef.value?.validate();
  const loadingInstance = ElLoading.service({ fullscreen: true });
  const response = await shios.post(apiName.value, { data: model.value });
  loadingInstance.close();
  console.log(response);
  reload?.();
}
type QrcodeFile = {
  id: number;
  createTime: string;
  fileName: string;
  pesticide: null | unknown;
  pesticideId: number;
};
async function preview(row: QrcodeFile) {
  if (!row) return;
  console.log(row);
  const { data } = await shios.get<string>('BatchQRCode/Preview', {
    path: row.id,
  });
  console.log(data);

  let href = router.resolve({ path: `pesicideinfo/details/${data}` }).href;
  console.log(href);

  window.open(router.resolve({ path: `pesicideinfo/details/${data}` }).href);
}
async function getFileURL(row: QrcodeFile) {
  if (!row) return;
  const res = await shios.get<string>('BatchQRCode/URL', { path: row.id });
  if (res.data) {
    onDownload(res.data, row.fileName);
  }
}
/**
 * 下载
 * @param { QrcodeFile }row
 */
async function onDownload(path: string, fileName: string): Promise<void> {
  // const response = await shios.download('BatchQRCode', { path: row.id });
  // console.log(response);
  // https://qrcode.dd100.cc/api/BatchQRCode/5?token=Bearer%20eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIxIiwidW5pcXVlX25hbWUiOiJhZG1pbiIsInJlZnJlc2hfdG9rZW5faWQiOiIzNmNkYzI2YzQ2NTU0NmQ2YTE1NzdhMDk5ZWIzZDI2OSIsIm5iZiI6MTY5NTkwMjM4MSwiZXhwIjoxNjk1OTA0MTgxLCJpYXQiOjE2OTU5MDIzODEsImlzcyI6ImRkMTAwIiwiYXVkIjoiY2xpZW50In0.EqqJ-euA0hYT_ZKK5N5C23Iir05ktRgtQEADQ7AFmBI
  // 创建一个隐藏的a标签
  let a = document.createElement('a');
  a.style.display = 'none';
  a.type = 'application/octet-stream';
  // a.target = '_blank';
  a.download = fileName ?? '123.txt';
  let url = `${shios.baseUrl}BatchQRCode/download/${path}`;
  // console.log(url);
  a.href = url;

  // a.href =
  //   'https://localhost:5001/QrcodeFiles/admin/test12309222318-ffb5c56c-ca95-4129-9139-b6970cb1c6b0.txt';
  document.body.appendChild(a);
  a.click(); // 触发a标签的click事件
  document.body.removeChild(a);
}
/**
 * 删除
 * @param {QrcodeFile} row
 */
async function onDelete(row: QrcodeFile) {
  console.log(row.id);
  await shios.delete('BatchQRCode', { path: row.id });
  reload?.();
}
</script>

<style lang="scss" scoped>
.el-form {
  // display: grid;
  // flex-wrap: wrap;
  // grid-template-columns: 1fr 1fr;
  width: 90%;
  margin: auto;
  // .el-form-item {
  //   flex: 1;
  //   min-width: 50%;
  //   max-width: 50%;
  //   padding: 0 4rem 0 2rem;
  // }
  .el-select {
    width: 100%;
  }
}
</style>
